
package com.powerunion.datacollection.report.excelreport.base.element;

import java.util.Map;

import com.powerunion.datacollection.report.excelreport.base.Parameter;
import com.powerunion.datacollection.report.excelreport.datasource.IDataSource;
import com.powerunion.datacollection.report.excelreport.util.AnalyseTempletTool;

/**
 * 字段类变量的实现一个字段类变量的具体实例，其代表了某个数据源中的某个具体的字段值。
 * @author juny
 */
public class FieldVariable extends Variable{
    public FieldVariable(String fieldTemplet){
        if(null != fieldTemplet && !"".equals(fieldTemplet)){
            setName(fieldTemplet);
            String[] temp = fieldTemplet.split(AnalyseTempletTool.DATASOURCE_FIELD_SEPARATOR_REGEX);
            if(null != temp && temp.length > 1){
                dsName = temp[0].trim();
                fieldName = temp[1].trim();
            }
        }
    }
    
    /*
     * (non-Javadoc)
     * @see net.excel.report.base.element.Variable#setParam(net.excel.report.base.Parameter)
     */
    public void setParam(Parameter param){
        this.setDataSource(param.dataSources);
    }
    
    /**
     * 设置参数变量的参数
     * @param dataSources
     */
    public void setDataSource(Map dataSources){
        if(null == ds){
            ds = (IDataSource)dataSources.get(dsName);
            //取得数据字段的类型
            String type = ds.getFieldType(fieldName);
            if(null != type){
                setValueType(type);
            }else{
                setValueType(UNKNOWN);
            }
        }
    }
    /* (non-Javadoc)
     * @see excel.report.util.Variable#getType()
     */
    public byte getType() {
        return VARIABLE_TYPE_FIELD;
    }
    /* (non-Javadoc)
     * @see excel.report.util.Variable#getValue()
     */
    public Object getValue() throws Exception {
        if(ds.size() <= 0){
            ds.queryData();
        }
        
        Object value = ds.getValue(fieldName);
        if(value != null){
            return getValueByType(value);
        }
        
        return null;
    }
    
    /*
     * (non-Javadoc)
     * @see net.excel.report.base.element.Variable#getString()
     */
    public String getString() throws Exception {
        if(ds.size() <= 0){
            ds.queryData();
        }
        
        Object value = ds.getValue(fieldName);
        if(value != null){
            return value.toString();
        }
        return "";
    }
    
    public String toString(){
        return "[" + dsName + "." +
        		fieldName + "]";
    }
    
    private String dsName = null;
    private String fieldName = null;
    private IDataSource ds = null;
}
